package com.jp.knowledge.activity;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.CommtemAdapter;
import com.jp.knowledge.adapter.FragMentAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.dialog.SkillDetailPopuWindow;
import com.jp.knowledge.fragment.SkillDetailFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpTabLayout;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/4/20.
 */

public class SkillDetailActivity extends SlidingActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, ResultSubscriber.OnResultListener, View.OnClickListener {

    private static final int REFRESH_CODE = 0x01;
    private static final int LOAD_MORE_CODE = 0x02;

    @ViewInject(R.id.top_bar)
    private RelativeLayout topBar;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;
    @ViewInject(R.id.can_content_view)
    private RecyclerView recyclerView;
    @ViewInject(R.id.shade_view)
    private View shadeView;

    @ViewInject(R.id.view_page)
    private ViewPager viewPager;
    private FragMentAdapter fragMentAdapter;

    /***
     * 筛选按钮
     */
    @ViewInject(R.id.filter_icon)
    private ImageView  filterIcon;

    private CommtemAdapter adapter;
    private List<HeadLineData> headLineDatas;
    private int page;
    private SkillDetailPopuWindow popuWindow;

    private List<PositionKnowlegeMode.ListBeanX> data;
    private int mainPosition;
    private int subPosition;

    private String id;
    /**
     * tab
     **/
    @ViewInject(R.id.tab_view)
    private TabView tabView;

    @Override
    protected int getResourceId() {
        return R.layout.activity_skill_detail;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        data = (List<PositionKnowlegeMode.ListBeanX>) intent.getSerializableExtra("data");
        mainPosition = intent.getIntExtra("mainPosition", 0);
        subPosition = intent.getIntExtra("subPosition", 0);
        if(data == null){
            onBackPressed();
            return;
        }
        final List<Fragment> framents = new ArrayList<>();

        framents.add(new SkillDetailFragment().settype(1));
        framents.add(new SkillDetailFragment().settype(2));
        framents.add(new SkillDetailFragment().settype(3));

        page = 1;
        headLineDatas = new ArrayList<>();
        popuWindow = new SkillDetailPopuWindow(mContext, topBar, data, mainPosition, subPosition);
        popuWindow.setOnItemSelectListener(new SkillDetailPopuWindow.OnItemSelectListener() {
            @Override
            public void onItemSelect(int mainPosition, int subPosition) {
                SkillDetailFragment fragment= (SkillDetailFragment) framents.get(viewPager.getCurrentItem());
                topName.setText(data.get(mainPosition).getList().get(subPosition).getName());
                SkillDetailActivity.this.mainPosition = mainPosition;
                SkillDetailActivity.this.subPosition = subPosition;
//                refreshLayout.autoRefresh();
                fragment.setValue(mainPosition,subPosition);
                fragment.refresh();
            }
        });
        popuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                shadeView.setVisibility(View.GONE);
            }
        });
        initTitleBar();
//        initView();

        setTabNames();
        fragMentAdapter = new FragMentAdapter(getSupportFragmentManager(), framents);

        viewPager.setAdapter(fragMentAdapter);
        tabView.setupWithViewPager(viewPager);

//        refreshLayout.autoRefresh();

        int tabIndex = intent.getIntExtra("tabIndex", 0);
        viewPager.setCurrentItem(tabIndex);
    }

    /**
     * 设置tab名称
     */
    protected void setTabNames() {
        tabView.setTabItems("最新", "最热", "精选");
    }

    private void initTitleBar(){
        filterIcon.setOnClickListener(this);
        topName.setText(data.get(mainPosition).getList().get(subPosition).getName());
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
//        rightIcon.setImageResource(R.mipmap.screeningclass);
        leftIcon.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
    }

    private void initView(){
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        headLineDatas = new ArrayList<>();
        adapter = new CommtemAdapter(mContext, headLineDatas);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                adapter.updateTitleColor(position);
                Intent intent = new Intent(mContext, InfoDataDetailActivity.class);
                intent.putExtra("id", headLineDatas.get(position).getId());
                intent.putExtra("type", headLineDatas.get(position).getType());
                intent.putExtra("linkTitle", headLineDatas.get(position).getTitle());
                try {
                    intent.putExtra("linkIcon", headLineDatas.get(position).getImglist().get(0).getSrc());
                }catch (Exception e){} finally {
                    startActivity(intent);
                }
            }
        });

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
    }

    @Override
    public void onRefresh() {
        getData(true);
    }

    @Override
    public void onLoadMore() {
        getData(false);
    }

    private void getData(boolean isRefresh){
        JsonObject param = new JsonObject();
        if(isRefresh) {
            page = 1;
            param.addProperty("page", page);
        } else{
            param.addProperty("page", ++page);
        }
        param.addProperty("type", 1);
        param.addProperty("navTypeId", data.get(mainPosition).getList().get(subPosition).getId());
        HttpHelper.getInstance(mContext).skillDetail(param,
                isRefresh?REFRESH_CODE:LOAD_MORE_CODE, this);
    }

    @Override
    public void onClick(View v) {
        if(v == leftIcon){
            onBackPressed();
        }  else if(v == rightIcon){
            SearchSimpleActivity.gotoSearch(mContext, id, 1, 2, 2);
        }else if(v == filterIcon){
            shadeView.setVisibility(View.VISIBLE);
            popuWindow.show();
        }
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        if(requestType == REFRESH_CODE){
            refreshLayout.refreshComplete();
        } else if(requestType == LOAD_MORE_CODE){
            refreshLayout.loadMoreComplete();
        }
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == REFRESH_CODE || requestType == LOAD_MORE_CODE){
            List<HeadLineData> datas = data.getList(HeadLineData.class);
            if(requestType == REFRESH_CODE)
                headLineDatas.clear();
            if(datas != null && datas.size() > 0)
                headLineDatas.addAll(datas);
            adapter.updataAdapter(headLineDatas);
        }
    }
}
